#pragma once
#include "index.hpp"
#include "util.hpp"
#include "log.hpp"
#include <jsoncpp/json/json.h>

namespace ns_searcher
{
    struct InvertedElemPrint
    {
        uint64_t doc_id;
        int weight;
        std::vector<std::string> words;
        InvertedElemPrint() :doc_id(0), weight(0){}
    };

    class Searcher
    {
    private:
        ns_index::Index* _index; //把Index类构建成单例模式， 供系统进行查询索引
    public:
        Searcher(){};
        ~Searcher(){};
    public:
        void InitSearcher(const std::string& input) //路径raw.txt文件路径
        {
            //1.获取或者创建Index对象
            _index = ns_index::Index::GetInstance();
            LOG(NORMAL, "获取index单例成功...");
            //2.根据Index对象建立索引
            _index->BuildIndex(input);
            LOG(NORMAL, "建立正排和倒排索引成功...");
        }
        //query :用户输入的搜索关键字， json_string :返回给用户浏览器的搜索结果
        void Search(const std::string& query, std::string* json_string)
        {
            //1. [分词]：对query进行按照searcher的要求继进行分词
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query, &words);
            //2. [触发]：根据分词的的结果，对每个词进行index查找
            std::vector<InvertedElemPrint> inverted_list_all; //用来保存不重复的倒排拉链
            std::unordered_map<uint64_t, InvertedElemPrint> tokens_map;
            for(std::string& word : words)
            {
                boost::to_lower(word);
                ns_index::InvertedList* inverted_list = _index->GetInvertList(word);
                if(nullptr == inverted_list)
                    continue;
                //去重的功能
                for(const auto& elem : *inverted_list)
                {
                    auto& item = tokens_map[elem.doc_id];
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight;
                    item.words.push_back(elem.word);
                }
            }
            for(const auto& item : tokens_map)
            {
                inverted_list_all.push_back(std::move(item.second));
            }
            //3。[合并排序]：汇总查找结果，根据weight进行降序排序
            std::sort(inverted_list_all.begin(), inverted_list_all.end(),\
                [](const InvertedElemPrint& e1, const InvertedElemPrint& e2){
                    return e1.weight > e2.weight;
                });
            //4. [构建]：根据查找的结果，构建json串 -- jsoncpp
            Json::Value root;
            for(auto& item : inverted_list_all)
            {
                ns_index::DocInfo* doc = _index->GetForwardIndex(item.doc_id);
                if(nullptr == doc)
                    continue;
                
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->content, item.words[0]); //是去标签的结果，不是我们想要的文章简介
                elem["url"] = doc->url;
                
                elem["id"] = (int)item.doc_id;
                elem["weight"] = item.weight;
                root.append(elem);
            }
            Json::StyledWriter writer;
            *json_string = writer.write(root);
        } 
        std::string GetDesc(const std::string& html_content, const std::string& word)
        {
            const std::size_t prev_step = 50;
            const std::size_t next_step = 100;
            //找到word在html_content这种的首次出现位置，提取word左右部分(前50个，后100个字符)的内容。
            auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), 
                [](int x, int y){return (std::tolower(x) == std::tolower(y));}
                );
            if(iter == html_content.end())
                return "None1";
            std::size_t word_pos = std::distance(html_content.begin(), iter);

            //获取desc区间
            std::size_t begin = 0;
            std::size_t end = html_content.size() - 1;
            if(word_pos > begin + prev_step) begin = word_pos - prev_step;
            if(word_pos + next_step < end) end = word_pos + next_step;
            
            if(begin >= end) return "None2";
            return html_content.substr(begin, end - begin);
        }
    };
}